package org.example.mybatisplus.controller;

import org.example.mybatisplus.dao.entity.Student;
import org.example.mybatisplus.dao.entity.SysUser;
import org.example.mybatisplus.service.IStudentService;
import org.example.mybatisplus.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生管理控制器 thymeleaf模板引擎实现页面跳转和数据处理
 */
@Controller
@RequestMapping("/userpage")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询学生列表信息
     * <p>

     * @return 学生信息
     */
    @GetMapping("/list")
    public String getStudentList(Model model, SysUser sysUser) {
        List<SysUser> list = null;
        if(sysUser != null && sysUser.getName() != null) {
            list = sysUserService.lambdaQuery().like(SysUser::getName,sysUser.getName()).list();
        }else{
            list = sysUserService.lambdaQuery().list();
        }

        model.addAttribute("list", list);
        return "user/list";
    }

    /**
     * 打开学生新增页面
     * <p>

     * @return 新增页面
     */
    @GetMapping("addpage")
    public String addpage(Model model, @ModelAttribute SysUser sysUser, @RequestParam(value = "id",required = false) Integer id){
        if(id != null){
            SysUser byId = sysUserService.getById(id);
            model.addAttribute("user",byId);
        }
        return "user/add";
    }

    /**
     * 保存用户信息
     * <p>
     * 根据用户ID查询学生对象详细信息。
     *
     * @param sysUser 学生对象
     * @return 学生对象
     */
    @PostMapping(value = {"/add", "/update"}, produces = "application/json")
    public String saveOrUpdate(Model model, @ModelAttribute("user") SysUser user,@Validated SysUser sysUser, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "user/add"; // 返回表单页面
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String result = encoder.encode(sysUser.getPwd());
        sysUser.setPwd(result);
        sysUserService.saveOrUpdate(sysUser);
        return getStudentList(model,sysUser);
    }


    /**
     * 删除学生信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @ResponseBody
    public String deleteUserById(Integer id) {
        sysUserService.removeById(id);
        return "success";
    }
}
